package com.zy.chat.mq;


import com.alibaba.fastjson.JSON;
import com.zy.chat.constants.constants;
import com.zy.chat.entity.GroupMessages;
import com.zy.chat.entity.SingleMessages;
import com.zy.chat.mapper.GroupMessageMapper;
import com.zy.chat.mapper.SingleMessageMapper;
import com.zy.chat.service.SaveGroupMessageService;
import com.zy.chat.vo.GroupmsgsDoc;
import com.zy.chat.vo.SinglemsgsDoc;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class GroupMsgListener {

    @Autowired
    private GroupMessageMapper groupMessageMapper;

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = constants.INSERT_QUEUE_NAME_GROUPMSG,durable = "true"),
            exchange = @Exchange(name=constants.EXCHANGE_NAME_GROUPMSG,durable = "tru1e",type = ExchangeTypes.TOPIC),
            key=constants.INSERT_KEY_GROUPMSG
    ))
    public void listenGroupmsgInsert(GroupMessages groupMessages){

        groupMessageMapper.insert(groupMessages);
        //转换文档
        GroupmsgsDoc groupmsgsDoc=new GroupmsgsDoc(groupMessages);
        IndexRequest request = new IndexRequest("singlemsg").id(groupMessages.getId().toString());
        request.source(JSON.toJSONString(groupmsgsDoc), XContentType.JSON);
        try {
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException("新增群聊聊消息失败");
        }
    }
}
